package orders

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"gorm.io/gorm"
	"insighttracking/apps/purchase/auth"
	"insighttracking/common/enum"
	"insighttracking/common/utils"
	"insighttracking/query/bo"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/purchase/internal/svc"
	"insighttracking/apps/purchase/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetOrdersPageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetOrdersPageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetOrdersPageApiLogic {
	hostname, _ := os.Hostname()
	return &GetOrdersPageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetOrdersPageApiLogic) GetOrdersPageApi(req *types.GetOrdersPageReq) (resp *types.GetOrdersPageResp, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	statusList := make([]int64, 0)
	if len(req.StatusList) > 0 {
		statusList = req.StatusList
	} else {
		statusList = []int64{enum.OrdersCreateEnum, enum.OrdersSortingProgressEnum, enum.OrdersSortingFinishEnum, enum.OrdersAlreadyShippedEnum, enum.OrdersCompletedEnum}
	}
	ordersBo, count, err := service.OrdersService.GetPageApi(l.ctx, bo.OrdersPageBoReq{
		EnterpriseID:     accountInfo.EnterpriseId,
		OrderNo:          req.OrderNo,          // 订单流水号
		StatusList:       statusList,           // 订单状态,0表示已下单(待采购),10分拣中，20已发货,30已完成,40取消订单
		StartDate:        req.StartDate,        // 开始时间，时间格式为:2024-12-12
		EndDate:          req.EndDate,          // 结束时间, 时间格式为:2024-12-12
		Name:             req.Name,             // 商品名称
		CustomerName:     req.CustomerName,     // 门店名称
		SettlementStatus: req.SettlementStatus, // 结算状态，0表示未结算,1表示已结算
		PageSize:         req.PageSize,         // 当前条数
		PageNumber:       req.PageNumber,       // 当前页数
		CustomerId:       req.CustomerId,       // 客户id,关联到enterprise_customer表主键id
	})
	if err != nil || len(ordersBo) == 0 {
		return &types.GetOrdersPageResp{
			Data: make([]types.GetOrdersResp, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      0,
				PageSize:   req.PageSize,
				PageNumber: req.PageNumber,
			},
		}, nil
	}
	var result = make([]types.GetOrdersResp, 0)
	for _, item := range ordersBo {
		// 查询详情
		var outStatus int64 // 出库状态 0表示待出库,10已出库，20部分出库,30已发货
		if k.IsContains([]int64{enum.OrdersAlreadyShippedEnum, enum.OrdersCompletedEnum}, item.Status) {
			outStatus = 30
		} else {
			goodsRecordEntity, err := service.SendGoodsRecordService.GetStoreSortingByOrderIdApi(l.ctx, item.ID)
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				detailEntities, err := service.OrdersDetailService.GetByOrderIdListApi(l.ctx, []int64{item.ID})
				storeDetailEntities, err := service.SendGoodsRecordDetailService.GetSendGoodsRecordDetailApi(l.ctx, goodsRecordEntity.ID)
				if err == nil && len(detailEntities) > 0 {
					if len(storeDetailEntities) >= len(detailEntities) {
						outStatus = 10
					} else {
						outStatus = 20
					}
				}
			}
		}
		var inStatus = service.PurchaseOrderService.GetPurchaseOrderStatusByOrderIdApi(l.ctx, item.ID) // 入库状态 0表示待入库,10已入库
		logx.WithContext(l.ctx).Infof("当前的状态:%v", inStatus)
		//// 1.查询全部的采购计划
		//detailEntities, err := service.OrdersDetailService.GetByOrderIdListApi(l.ctx, []int64{item.ID})
		//if err == nil && len(detailEntities) > 0 {
		//	orderDetailIdList := k.Map(detailEntities, func(item *model.OrdersDetailEntity, index int) int64 {
		//		return item.ID
		//	})
		//	// 2.查询采购计划
		//	planOrdersEntities, err := service.PurchasePlanOrdersService.GetByOrdersDetailIdListApi(l.ctx, orderDetailIdList)
		//	if err == nil && len(planOrdersEntities) > 0 {
		//		planIdList := k.Map(planOrdersEntities, func(item *model.PurchasePlanOrdersEntity, index int) int64 {
		//			return item.PurchasePlanID
		//		})
		//		purchaseOrdersDetailEntities, err := service.PurchaseOrderDetailService.GetByPurchasePlanIdListApi(l.ctx, planIdList)
		//		if err == nil && len(purchaseOrdersDetailEntities) > 0 {
		//			isOk := k.Every(purchaseOrdersDetailEntities, func(item *model.PurchaseOrdersDetailEntity, index int) bool {
		//				return item.StoreStatus == 10
		//			})
		//			if isOk {
		//				inStatus = 10
		//			}
		//		}
		//	}
		//
		//}

		// 查询出库数据
		result = append(result, types.GetOrdersResp{
			ID:                 item.ID,                                                                           // 主键id
			OrderNo:            item.OrderNo,                                                                      // 订单流水号
			EnterpriseID:       item.EnterpriseID,                                                                 // 关联到enterprise表主键id
			CustomerID:         item.CustomerID,                                                                   // 客户id,关联到enterprise_customer表主键id
			CustomerName:       item.CustomerName,                                                                 // 门店名称
			SendGoodsDate:      k.If(item.SendGoodsDate.IsZero(), 0, utils.TimestampToString(item.SendGoodsDate)), // 发货日期
			SendGoodsMethod:    item.SendGoodsMethod,                                                              // 发货方式,0表示司机配送
			SettlementMethod:   item.SettlementMethod,                                                             // 结算方式，0表示账期
			PurchaserID:        item.PurchaserID,                                                                  // 采购员,关联到
			PurchaserName:      item.PurchaserName,                                                                // 采购员名称
			Remark:             item.Remark,                                                                       // 订单备注
			TotalAmount:        item.TotalAmount.StringFixed(2),                                                   // 订单金额
			TotalCount:         item.TotalCount.StringFixed(2),                                                    // 订单商品数量
			Status:             item.Status,                                                                       // 订单状态,0表示已下单(待采购),1表示采购中,2表示已采购,3待入库，4已入库，5已发货,6已收货,7表示退货
			ReceiveGoodsName:   item.ReceiveGoodsName,                                                             // 收货员姓名
			ReceiveGoodsMobile: item.ReceiveGoodsMobile,                                                           // 收货人手机号码
			ReceiveAddress:     item.ReceiveAddress,                                                               // 收货人地址
			IsPurchasingPlan:   item.IsPurchasingPlan,                                                             // 是否发布采购计划,0表示不发布,1表示发布
			Source:             item.Source,                                                                       // 订单来源,0表示app端,1表示pc下单
			SettlementStatus:   item.SettlementStatus,                                                             // 结算状态，0表示未结算,1表示已结算
			SendGoodsID:        item.SendGoodsID,                                                                  // 配置司机,关联到account表主键id
			SendGoodsName:      item.SendGoodsName,                                                                // 配送司机名称
			WarehouseID:        item.WarehouseID,                                                                  // 发货仓库,关联到warehouse表主键id
			WarehouseName:      item.WarehouseName,                                                                // 仓库名称
			CreatedAt:          utils.TimestampToString(item.CreatedAt),                                           // 创建时间
			UpdatedAt:          utils.TimestampToString(item.UpdatedAt),                                           // 更新时间
			OutStatus:          outStatus,                                                                         // 出库状态 0表示待出库,10已出库，20部分出库,30已发货
			InStatus:           inStatus,                                                                          // 入库状态 0表示待入库,10已入库
		})
	}
	return &types.GetOrdersPageResp{
		Data: result,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
	}, nil
}
